import {simpleGet, simplePost} from "../../../utils/request";
import {getLoginUser} from "../../../service/user";
import orderService, {getCacheOrder, prepareOrder} from "../../../service/order";
import {showToast} from "../../../utils/tool";
import {getSite} from "../../../service/site";

const app = getApp()
const global = app.globalData

Page({
    data: {
        nav:{
            title:"下单",
        },
        user:null,
        options:{},
        info:null,
        imageUrl:global.imageUrl,
        payLoading:false,
        site:null,
    },
    onLoad: function (options={}) {
        this.init(options)
    },

    /**
     * 修改收货地址
     */
    changeAddress(){

        wx.navigateTo({
            url: `/pages/user/address/index?use_select=1`,
            events:{
                // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                selectUserAddressEvent: ({address}) => {
                    console.log("address", address)
                    this.setData({
                        [`info.address_id`]: address.id,
                        [`info.userAddress`]: address
                    })
                    // 更新订单信息
                    // this.updateRealOrder()
                },
            },
        })
    },

    numChange(e){
        const {value} = e.detail
        const {itemIndex} = e.currentTarget.dataset
        const {info} = this.data

        info.items[itemIndex].num = value
        this.setOrder(info)

    },

    /**
     * 切换支付方式
     * @param e
     */
    payTypeChange(e){
        const {value} = e.detail
        this.setData({
            [`info.pay_type`]:value,
        })
    },

    // 优惠券
    couponChange(e){
        const detail = e.detail
        const {info} = this.data
        this.setOrder({...info, ...detail})
    },

    /**
     * 是否使用积分
     */
    pointsChange(e){
        const {user, info} = this.data
        const {value} = e.detail
        info.points_num = value ? user.points : 0
        this.setOrder(info)
    },

    /**
     * 备注
     */
    editNote(e){
        console.log("note",e)
        const {value} = e.detail
        this.setData({
            [`info.user_note`]:value,
        })
    },
    payOrder(e){

        // return;

        // this.setData({
        //     payLoading:true,
        // })

        const {info} = this.data

        // 订单验证
        const isNotExpress = info.items.some(item => !item.isExpressDelivery)
        if (isNotExpress){
            showToast("订单中包含不支持配送的商品")
            return;
        }
        if (!info.pay_type){
            showToast("请选择付款方式")
            return;
        }
        if (!info.userAddress){
            showToast("请选择收货地址")
            return;
        }

        this.setData({
            payLoading:true,
        })

        if (info.id){   // 已经创建订单，直接付款

        }else{  // 未创建订单
            simplePost("/order/create", info).then(r => {

                orderService.payment(r.info).then(success => {
                    let url = '/pages/user/order_pay/pay_result'

                    if (info.order_type == 'group' && info.is_single == 0){  // 拼团订单，且不是单独购买，进入拼团分享页
                        url = '/pages/user/active/group_share'
                    }

                    wx.redirectTo({
                        url,
                    })
                })

            })
        }

    },

    payOrderHandle(){

    },

    /**
     * 获取订单
     * 从后台请求新的订单信息，并返回
     * @param order
     * @returns {Promise<unknown>}
     */
    setOrder(order) {
        prepareOrder(order).then(r => {
            this.setData({
                info:r,
            })
        })
    },
    /**
     * 更新订单
     * 从后台请求新的订单信息，并替换现有订单
     */
    updateRealOrder(){
        const {info} = this.data
       this.getRealOrder(info).then(r => {
           this.setData({
               info:r
           })
       })
    },

    async init(options){
        const user = await getLoginUser(true)
        const site = await getSite()
        let order = getCacheOrder() // 客户选择的下单商品信息
        this.setData({
            user,
            options:options,
            site,
        })

        // 设置订单信息
        this.setOrder(order)
    }

});
